package org.idea.spring.datasource.dbcp.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.idea.spring.datasource.bean.User;
import org.idea.spring.datasource.dbcp.DbcpDataSourceConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author linhao
 * @Date created in 2:56 下午 2021/5/17
 */
@Component
@ConditionalOnClass(DruidDataSource.class)
public class DataSourceService {

//    @Resource
//    private BasicDataSource basicDataSource;
    @Resource
    private DruidDataSource druidDataSource;

    @Resource
    private Environment environment;


    public void doTest() throws SQLException {
        String value = environment.getProperty("qiyu.default.datasource.type");
        System.out.println("datasource type is : " + value);
        Connection connection = druidDataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user limit 1");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setUsername(resultSet.getString("username"));
            System.out.println(user);
        }
        connection.close();
    }
}
